
try {



// 原来与C++层的接口 ------------------------------------

var __interface_gnet_sendHttp = function (url, params, isPost, tag) {

    var xhr = new XMLHttpRequest();
    var method = isPost ? "POST" : "GET"
    if(isPost) {
        xhr.open(method, url);
        cc.log('[__send]'+url);
    } else {
        xhr.open(method, url+"?"+params);
        cc.log('[__send]'+url+"?"+params);
    }

    var that = this;
    xhr.onreadystatechange = function() {
        if(xhr.status == 200) {
            __interface_gnet_on_data(xhr.responseText, tag);
        }
    }
    if(isPost) {
        xhr.send(params);
    } else {
        xhr.send();
    }
}


/*
//ASCII 转换 Unicode  
function AsciiToUnicode(content) {  
    result = '';  
    for (var i=0; i<content.length; i++){
        // result+='\\x' + content.charCodeAt(i) + ';';  
        result+='&#' + content.charCodeAt(i) + ';';  
    }       
    return result;
}  
//Unicode 转换 ASCII  
function UnicodeToAscii(content) {   
    var code = content.match(/&#(\d+);/g);  
    result= '';  
    for (var i=0; i<code.length; i++){
        result += String.fromCharCode(code[i].replace(/[&#;]/g, ''));  
    }       
    return result;
} 
*/

// callback from c++
var __interface_gnet_on_data = function (data, tag) {
    gnet.onData(data, tag);
}


// gnet ------------------------------------

var gnet = {

	serverUrl : "",
	funcCmdHandler : null,
	nextTag : 0,
	callbacks : {},
	sessionKey : null,
    
    encodeKey : 1234567890,


	setCmdHandler : function (func) {
		this.funcCmdHandler = func;
	},


	setServerUrl : function (serverUrl) {
		if (serverUrl[serverUrl.length-1] != '/') serverUrl += '/'
		this.serverUrl = serverUrl;
	},

	setSessionKey : function (sessionKey) {
		this.sessionKey = sessionKey;
	},
	
	onData : function (buff, tag) {
		if (tag in this.callbacks)
		{
            func = this.callbacks[tag];
            delete this.callbacks[tag];

            cc.log("gnet>[RECV] " + buff);

            var data = JSON.parse(buff);    // 字符串转成js对象
            
            if(data['err']) {
                // 出错信息
                cc.log(data['err']);
            } else {
                // 提示信息
                if(data['msg']) { cc.log(data['msg']); }
                // 逻辑处理
                if(func) { func(data); }
            }

            // 处理服务端命令
            if(data['cmd']) {
                if(this.funcCmdHandler) { this.funcCmdHandler(data['cmd']); }
            }
		}
	},


	// 发送网络请求
	// params : 可以是Object 或者 null
	sendHttp : function (url, params, func) {
		if(params == null) params = {};

		if(typeof(params) == 'object') {
			params = 'p=' + JSON.stringify(params);	// JSON对象有两个方法：stringify()和parse()
		} else {
			cc.log('gnet>send | params MUST be Object');
		}

		// 加上sessionKey
		if(this.sessionKey != null) params += '&sk=' + this.sessionKey;

		// 加上随机数
		params += '&rand=' + Math.random();

		cc.log('gnet>[SEND] ' + url + '  ' + params);

		url = this.serverUrl + url;
		__interface_gnet_sendHttp(url, params, false, this.nextTag);
		this.callbacks[this.nextTag] = func;
		this.nextTag += 1;
	}, 
    

    // 足球发送
    // m:要调用的服务器端的模块名
    // f:要调用的服务器端的模块的方法名
    // p:传递的参数，如果有多个参数 使用数组封装 如:[p1,p2]
    // st:本地时间加上本地与服务器时间的时间差的值 在登入成功后，会通知服务器时间戳。时间戳以秒为单位
    // c:调用唯1标识，用于客户端在收到返回时辨认该返回是属于哪一次请求的
    /*
    sendFB : function (m, f, p, callback) {
		url = this.serverUrl + this.sessionKey;
        st = parseInt((new Date()).getTime() / 1000);
        c = 0;
        //params = [{'m':m, 'f':f, 'p':p, 'st':st, 'c':c}];
        params = [{'m':m, 'f':f, 'p':p}];
		
        cc.log('gnet>[SEND] ' + url + '?' + JSON.stringify(params));
        
		__interface_gnet_sendHttp(url, this._encode(params), false, this.nextTag);
		this.callbacks[this.nextTag] = callback;
		this.nextTag += 1;
    },
    */
    
    // 发送原始http请求
    sendHttpRaw : function (url, callback) {
        __interface_gnet_sendHttp(url, "", false, this.nextTag);
		this.callbacks[this.nextTag] = callback;
		this.nextTag += 1;
    },
    
    // 数据混淆
    _encode : function (data) {
        var buff = JSON.stringify(data);
        
        //cc.log('_encode:'+buff);
        buff = base64encode(buff);
        var cut = this.encodeKey % buff.length;
        return buff.substring(cut, buff.length) + buff.substring(0, cut);
    },
    
    _decode : function (data) {
        //cc.log('gnet._decode:'+data);
        var cut = data.length - (this.encodeKey % data.length);
        var buff = data.substring(cut, data.length) + data.substring(0, cut);
        buff = base64decode(buff);
        try {
            //cc.log('gnet._decode:'+buff);
            return JSON.parse(buff);
        } catch (e) {
            cc.log('返回数据格式错误');
            return null;
        }
    },

}


// cmd handler ------------------------------
// 处理服务器返回的特殊指令
function cmdHandler(cmd) {

	switch(cmd) {
		// 重新登陆
		case 'relogin':
			UIManager.changeSceneWelcome();
			break;
		default:
			cc.log('gnet>cmdHandler unkown cmd : ' + cmd);
	}

}

gnet.setCmdHandler(cmdHandler)


} catch(e) {log(e);}
